package com.mall.user.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

import static org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
import static org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus.RECONSUME_LATER;

@Component
public class MailConsumer {
    private DefaultMQPushConsumer consumer;

    @Autowired
    JavaMailSender mailSender;
    @PostConstruct
    public void init(){
        consumer = new DefaultMQPushConsumer("verifyMail-consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        try {
            consumer.subscribe("verifyMail","*");
            consumer.registerMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                    MessageExt msg = list.get(0);
                    String msgStr = new String(msg.getBody());
                    JSONObject map = JSON.parseObject(msgStr);
                    //发送短信
                    SimpleMailMessage message = new SimpleMailMessage();
                    message.setSubject((String) map.get("topic"));
                    message.setText((String) map.get("text"));
                    message.setFrom((String) map.get("from"));
                    message.setTo((String) map.get("to"));
                    message.setCc("irajames4j@163.com");
                    try {
                        mailSender.send(message);
                    }catch (Exception e){
                        return RECONSUME_LATER;
                    }
                    return CONSUME_SUCCESS;
                }
            });
        } catch (MQClientException e) {
            e.printStackTrace();
        }
        try {
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }
}
